package inventoryServe.controller;




import inventoryServe.po.Supplier;

import inventoryServe.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import inventoryServe.utils.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-06-22
 */
@Controller
public class SupplierController {
    @Autowired
    private SupplierService supplierService;

    // 获取供应商列表数据
    @GetMapping("/suppliers")
    @ResponseBody
    public Object allSupplier(HttpServletRequest req) {

        String name = req.getParameter("name").trim();
        Supplier supplier = new Supplier();
        if (name != "") {
           supplier.setName(name);
        }

        List<Supplier> res = this.supplierService.allSupplier(supplier);
        if (res != null) {
            return ResUtils.Success(1,"查询成功",res);
        } else {
            return ResUtils.Fail(0,"没有数据");
        }
    }


    // 根据 id 获取供应商信息
    @GetMapping("/suppliers/{id}")
    @ResponseBody
    public Object supplierOfId(@PathVariable("id") Integer id) {

        Supplier res = supplierService.supplierOfId(id);
        if (res != null) {
            return ResUtils.Success(1,"查询成功",res);
        } else {
            return ResUtils.Fail(0,"没有数据");
        }
    }


    // 删除供应商
    @DeleteMapping("suppliers/{id}")
    @ResponseBody
    public Object deleteSupplier(@PathVariable("id") Integer id) {
        boolean res = supplierService.deleteSupplier(id);

        if (res) {
            return ResUtils.Success(1,"删除成功");
        } else {
            return ResUtils.Fail(0,"删除失败");
        }
    }

    // 增加供应商
    @PostMapping("suppliers/")
    @ResponseBody
    public Object addSupplier(@RequestBody Supplier supplier) {
        System.out.println(supplier);

        Date now = new Date();
        supplier.setCreateTime(now);
        supplier.setUpdateTime(now);
        System.out.println(supplier);
        boolean res = supplierService.addSupplier(supplier);

        if (res) {
            return ResUtils.Success(1,"添加成功",supplier);
        } else {
            return ResUtils.Fail(0,"添加失败");
        }
    }


    // 根据 id 修改供应商信息
    @PutMapping("/suppliers/{id}")
    @ResponseBody
    public Object editSupplier(@PathVariable("id") Integer id, @RequestBody Supplier supplier) {

        Date now = new Date();
        supplier.setUpdateTime(now);

        System.out.println(supplier);

        Boolean res = supplierService.editSupplier(supplier);

        if (res) {
            return ResUtils.Success(1, "修改成功",supplier);
        } else {
            return ResUtils.Fail(0, "修改失败");
        }
    }


}

